<template>
  <!-- 主容器：全屏布局 -->
  <el-container style="height: 100vh; width: 100%">
    <!-- 顶部导航栏 -->
    <el-header class="header-container">
      <!-- 顶部水平菜单 -->
      <el-menu
        class="el-menu-demo"
        mode="horizontal"
        background-color="rgba(0, 82, 217, 1)"
        text-color="#fff"
        active-text-color="#ffd04b"
      >
        <!-- 系统 Logo 区域 -->
        <el-menu-item divided @click="Introduction" style="width: 200px">
          <div id="u3708" class="ax_default _默认样式">
            <div id="u3708_div" class=""></div>
            <div id="u3708_text" class="text">
              <p><span>ERP&amp;MES</span></p>
            </div>
          </div>
        </el-menu-item>

        <!-- 顶部菜单项：循环渲染菜单数据 -->
        <el-menu-item
          class="el-menu-item-host"
          @click="getMenu(item.children)"
          v-for="item in menu"
        >
          {{ item.name }}
        </el-menu-item>
      </el-menu>

      <!-- 用户信息区域：右侧显示，鼠标悬停显示下拉菜单 -->
      <div class="user-info-container">
        <div class="theme-toggle">
          <el-switch
            v-model="isDarkMode"
            inline-prompt
            active-text="深色"
            inactive-text="浅色"
            :active-icon="Moon"
            :inactive-icon="Sunny"
            @change="handleThemeToggle"
          />
        </div>
        <el-dropdown trigger="hover" placement="bottom-end">
          <span class="user-info">
            <el-icon class="user-icon">
              <User />
            </el-icon>
            <span class="username">{{ currentUser.name }}</span>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <!-- 编辑信息选项 -->
              <el-dropdown-item @click="handleEditInfo">
                <el-icon>
                  <Edit />
                </el-icon>
                编辑信息
              </el-dropdown-item>
              <el-dropdown-item @click="upPassWork">
                <el-icon>
                  <Unlock />
                </el-icon>
                修改密码
              </el-dropdown-item>
              <!-- 退出登录选项 -->
              <el-dropdown-item divided @click="retreat">
                <el-icon>
                  <SwitchButton />
                </el-icon>
                退出登录
              </el-dropdown-item>
              <!-- <el-dropdown-item divided @click="Introduction">
                <el-icon>
                  <Grid />
                </el-icon>
                操作引导
              </el-dropdown-item> -->
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>
    <!-- 主体内容区域 -->
    <el-container>
      <!-- 左侧边栏：带滑入动画 -->
      <transition name="sidebar-slide">
        <el-aside width="300px" class="sidebar-container">
          <!-- 垂直菜单：显示当前选中菜单的子菜单项 -->
          <el-menu
            active-text-color="#ffd04b"
            background-color="#333333"
            class="el-menu-vertical-demo"
            default-active="2"
            text-color="#fff"
            style="height: 100%"
            router
          >
            <!-- 循环渲染子菜单项 -->
            <el-menu-item v-for="item in Host" :index="item.url">{{ item.name }}</el-menu-item>
          </el-menu>
        </el-aside>
      </transition>
      <!-- 主内容区域 -->
      <el-main>
        <!-- 已访问页面快捷标签 -->
        <div class="tab-history-bar" v-if="visitedTabs.length">
          <el-tabs
            v-model="activeTab"
            type="card"
            @tab-click="handleTabClick"
            @tab-remove="handleTabRemove"
            stretch
          >
            <el-tab-pane
              v-for="tab in visitedTabs"
              :key="tab.path"
              :label="tab.title"
              :name="tab.path"
              :closable="tab.closable"
            />
          </el-tabs>
        </div>
        <el-scrollbar height="1133px">
          <!-- 内容区域：显示路由组件 -->
          <div class="content-wrapper">
            <RouterView />
          </div>
        </el-scrollbar>
      </el-main>
    </el-container>
  </el-container>
</template>

<script lang="ts" setup>
/**
 * 首页组件
 * 功能：系统主界面，包含顶部导航、侧边栏和内容区域
 */

// ==================== 导入模块 ====================
import { onMounted, ref, watch } from 'vue' // Vue 组合式 API
import { useRoute, useRouter } from 'vue-router' // Vue Router 路由
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import type { TabPaneName, TabsPaneContext } from 'element-plus'
import {
  User,
  Edit,
  SwitchButton,
  Operation,
  Box,
  Document,
  DataAnalysis,
  Unlock,
  Moon,
  Sunny,
} from '@element-plus/icons-vue' // Element Plus 图标组件
import { useCounterStore } from '@/stores/counter' // Pinia 状态管理

// ==================== 初始化 ====================
const store = useCounterStore() // Pinia store 实例，用于获取用户信息
const router = useRouter() // 路由实例，用于页面跳转
const route = useRoute()

/**
 * 当前登录用户信息
 * @property {string} name - 用户真实姓名
 * @property {string} avatar - 用户头像（当前未使用）
 */
const currentUser = ref({
  name: store.userinfo.realname, // 从 store 获取用户真实姓名
  avatar: '', // 头像地址（预留）
})

/**
 * 顶部导航菜单数据
 * 模拟用户权限数据，包含菜单名称和子菜单项
 * @property {number} id - 菜单 ID
 * @property {string} name - 菜单名称
 * @property {Array} children - 子菜单项数组
 *   @property {number} children.id - 子菜单 ID
 *   @property {string} children.name - 子菜单名称
 *   @property {string} children.url - 子菜单路由地址
 */
const menu: any = ref([
  {
    id: 1,
    name: '生产',
    children: [
      {
        id: 1,
        name: '甘特图(单科铭 物联网-智能 MES 生产管理系统-生产计划管理)',
        url: '/Scheduling',
      },
      {
        id: 2,
        name: '工作台(李思俊)',
        url: '/Workbench',
      },
      {
        id: 3,
        name: '质检管理(李思俊)',
        url: '/Qualitylist',
      },
    ],
  },
  {
    id: 3,
    name: '物品',
    children: [
      {
        id: 1,
        name: '(BOM管理-张晓亮)',
        url: '/BOMlist',
      },
      {
        id: 2,
        name: '工艺工序(张晓亮)',
        url: '/MakestepView',
      },
    ],
  },
  {
    id: 4,
    name: '采购',
    children: [
      {
        id: 1,
        name: '待定',
        url: '/',
      },
    ],
  },
  {
    id: 5,
    name: '仓库',
    children: [
      {
        id: 1,
        name: '巷道管理',
        url: '/Laneway',
      },
    ],
  },
  {
    id: 6,
    name: '用户管理',
    children: [
      {
        id: 1,
        name: '用户管理',
        url: '/QuseryUser',
      },
      {
        id: 2,
        name: '角色管理',
        url: '/RoleManagement',
      },
      {
        id: 3,
        name: '部门管理',
        url: '/DepartmentManagement',
      },
      {
        id: 4,
        name: '权限管理',
        url: '/PermissionManagement',
      },
    ],
  },
])

// const menu: any = store.menu

/**
 * 侧边栏菜单数据
 * 存储当前选中顶部菜单的子菜单项，用于在侧边栏显示
 */
const Host: any = ref([])

type VisitedTab = {
  path: string
  title: string
  closable: boolean
}

const defaultLandingPath = '/Introduction'
const routeTitleMap: Record<string, string> = {
  '/Introduction': '操作引导',
  '/Scheduling': '生产计划',
  '/Workbench': '工作台',
  '/Qualitylist': '质检管理',
  '/BOMlist': 'BOM管理',
  '/BOMdetails': 'BOM详情',
  '/MakestepView': '工艺工序',
  '/MakestepdetailsView': '工序详情',
  '/Userinfo': '个人信息',
  '/Passwork': '修改密码',
  '/addquality': '新增质检',
  '/QuseryUser': '用户管理',
  '/qualitywork': '车间质检',
  '/qualityorder': '订单质检',
}

const visitedTabs = ref<VisitedTab[]>([
  {
    path: defaultLandingPath,
    title: routeTitleMap[defaultLandingPath] || '默认页面',
    closable: false,
  },
])
const activeTab = ref(defaultLandingPath)
const themeStorageKey = 'app-theme'
const isDarkMode = ref(false)

onMounted(() => {
  // 组件挂载时执行（当前为空，getMenu 未调用）
  getMenu(menu.value[0].children)
  initTheme()
})

const resolveTabTitle = (targetRoute: RouteLocationNormalizedLoaded) => {
  return (
    (targetRoute.meta?.title as string) ||
    routeTitleMap[targetRoute.path] ||
    (targetRoute.name as string) ||
    '未命名页面'
  )
}

const ensureTabVisible = (targetRoute: RouteLocationNormalizedLoaded) => {
  const path = targetRoute.path
  if (!path || path === '/Home') return
  const exists = visitedTabs.value.some((tab) => tab.path === path)
  if (!exists) {
    visitedTabs.value.push({
      path,
      title: resolveTabTitle(targetRoute),
      closable: path !== defaultLandingPath,
    })
  }
  activeTab.value = path
}

watch(
  () => route.fullPath,
  () => {
    ensureTabVisible(route)
  },
  { immediate: true }
)

const handleTabClick = (pane: TabsPaneContext) => {
  const targetPath = pane.paneName as string
  if (targetPath && targetPath !== route.path) {
    router.push(targetPath)
  }
}

const handleTabRemove = (targetName: TabPaneName) => {
  const tabs = visitedTabs.value
  const tabIndex = tabs.findIndex((tab) => tab.path === targetName)
  if (tabIndex === -1) return
  const targetTab = tabs[tabIndex]
  if (!targetTab) return
  if (!targetTab.closable) return
  const isActive = activeTab.value === targetName
  tabs.splice(tabIndex, 1)
  if (isActive) {
    const nextTab = tabs[tabIndex] || tabs[tabIndex - 1] || tabs[0]
    if (nextTab) {
      router.push(nextTab.path)
    } else {
      router.push(defaultLandingPath)
    }
  }
}

const applyThemeClass = (dark: boolean) => {
  if (typeof document === 'undefined') return
  const root = document.documentElement
  root.classList.remove('theme-light', 'theme-dark')
  root.classList.add(dark ? 'theme-dark' : 'theme-light')
  document.body.setAttribute('data-theme', dark ? 'dark' : 'light')
  if (typeof localStorage !== 'undefined') {
    localStorage.setItem(themeStorageKey, dark ? 'dark' : 'light')
  }
}

const initTheme = () => {
  if (typeof window === 'undefined') return
  const saved = localStorage.getItem(themeStorageKey)
  if (saved) {
    isDarkMode.value = saved === 'dark'
  } else {
    const prefersDark = window.matchMedia?.('(prefers-color-scheme: dark)').matches
    isDarkMode.value = !!prefersDark
  }
  applyThemeClass(isDarkMode.value)
}

const handleThemeToggle = (value: boolean) => {
  applyThemeClass(value)
}

/**
 * 获取菜单子项并更新侧边栏
 * 点击顶部菜单时调用，将子菜单项赋值给 Host
 * @param {Array} children - 子菜单项数组
 */
const getMenu = (children: any) => {
  Host.value = children // 更新侧边栏菜单数据
}

/**
 * 处理编辑信息操作
 * 跳转到个人信息页面（子路由）
 */
const handleEditInfo = () => {
  // 跳转到子路由，路径为 /home/userinfo
  router.push('UserInfo')
}

const upPassWork = () => {
  router.push('PassWork')
}

/**
 * 退出登录
 * 清除用户信息并跳转到登录页
 */
const retreat = () => {
  // store.userinfo.realname = '' // 清除 store 中的用户真实姓名
  router.push('/') // 跳转到登录页面
  localStorage.removeItem('realname')
}

const Introduction = () => {
  router.push('/Introduction') // 跳转到登录页面
}
</script>

<style>
/**
 * ==================== 全局样式 ====================
 */

/* 全局重置样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

:root {
  --app-bg-color: #f5f7fa;
  --app-text-color: #1f2933;
  --content-bg-color: #f3f5f7;
  --panel-bg-color: #ffffff;
  --header-bg-color: rgba(0, 82, 217, 1);
  --header-text-color: #ffffff;
  --sidebar-bg-color: #333333;
  --border-color: #e5e7eb;
}

.theme-dark {
  --app-bg-color: #0f172a;
  --app-text-color: #f8fafc;
  --content-bg-color: #111827;
  --panel-bg-color: #1f2937;
  --header-bg-color: #1e293b;
  --header-text-color: #f8fafc;
  --sidebar-bg-color: #111827;
  --border-color: #374151;
}

.theme-light {
  --app-bg-color: #f5f7fa;
  --app-text-color: #1f2933;
  --content-bg-color: #f3f5f7;
  --panel-bg-color: #ffffff;
  --header-bg-color: rgba(0, 82, 217, 1);
  --header-text-color: #ffffff;
  --sidebar-bg-color: #333333;
  --border-color: #e5e7eb;
}

/* 全局容器样式（非 scoped） */
html,
body,
#app {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
}

body {
  background-color: var(--app-bg-color);
  color: var(--app-text-color);
  transition: background-color 0.3s ease, color 0.3s ease;
}
</style>

<style scoped>
/**
 * ==================== 组件样式 ====================
 */

/* 主内容区域样式 */
.el-main {
  --el-main-padding: 0px;
  box-sizing: border-box;
  display: block;
  flex: 1;
  flex-basis: auto;
  overflow: auto;
  /* 允许内容滚动 */
  padding: var(--el-main-padding);
  position: relative;
  /* 相对定位，用于子元素定位 */
  background-color: var(--app-bg-color);
  color: var(--app-text-color);
  transition: background-color 0.3s ease, color 0.3s ease;
}

/* 内容区域包装器 - 确保内容可以正常滚动 */
.content-wrapper {
  width: 100%;
  height: 1133px;
  box-sizing: border-box;
  background-color: var(--content-bg-color);
  transition: background-color 0.3s ease;
}

.tab-history-bar {
  background-color: var(--panel-bg-color);
  border-bottom: 1px solid var(--border-color);
  padding: 8px 16px;
  transition: background-color 0.3s ease, border-color 0.3s ease;
}

.tab-history-bar :deep(.el-tabs__header) {
  margin-bottom: 0;
}

.tab-history-bar :deep(.el-tabs__item) {
  user-select: none;
  color: var(--app-text-color);
}

/* .el-menu--horizontal > .el-menu-item:nth-child(5) {
  margin-right: auto;
} */

/**
 * ==================== 顶部导航栏样式 ====================
 */

/* 顶部导航栏容器 */
.el-header {
  --el-header-padding: 0;
  --el-header-height: 60px;
  box-sizing: border-box;
  flex-shrink: 0;
  height: var(--el-header-height);
  padding: var(--el-header-padding);
}

/* 顶部导航栏容器布局 */
.header-container {
  display: flex;
  align-items: center;
  background-color: var(--header-bg-color);
  color: var(--header-text-color);
  /* 蓝色背景 */
  position: relative;
}

.el-menu {
  background-color: transparent;
  border-right: 1px solid var(--el-menu-border-color);
  box-sizing: unset;
  list-style: none;
  margin: 0;
  padding-left: 0;
  position: relative;
  flex: 1;
}

::deep(.el-menu--horizontal .el-menu-item) {
  color: var(--header-text-color);
}

#u3708 {
  border-width: 0px;
  position: absolute;
  left: 0px;
  top: 0px;
  width: 200px;
  height: 60px;
  display: flex;
  font-family: '微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑', sans-serif;
  font-weight: 700;
  font-style: normal;
  font-size: 20px;
  color: var(--header-text-color);
  line-height: 28px;
}

.ax_default {
  font-family: 'Arial Normal', 'Arial', sans-serif;
  font-weight: 400;
  font-style: normal;
  font-size: 13px;
  letter-spacing: normal;
  color: #333333;
  vertical-align: none;
  text-align: center;
  line-height: normal;
  text-transform: none;
}

#u3708 .text {
  position: absolute;
  align-self: center;
  padding: 0px 0px 0px 0px;
  box-sizing: border-box;
  width: 100%;
}

.el-menu-item-host {
  height: 60px;
  width: 60px;
  margin: 2px;
  transition: all 0.3s ease;
  border-radius: 4px;
  position: relative;
}

/* 顶部导航栏菜单项 hover 样式 */
:deep(.el-menu--horizontal .el-menu-item-host:hover) {
  background-color: rgba(255, 255, 255, 0.15) !important;
  transform: translateY(-2px);
}

/* 顶部导航栏菜单项 active 样式 */
:deep(.el-menu--horizontal .el-menu-item-host.is-active) {
  background-color: rgba(255, 255, 255, 0.2) !important;
  color: #ffd04b !important;
  font-weight: 600;
}

/* 顶部导航栏菜单项点击效果 */
:deep(.el-menu--horizontal .el-menu-item-host:active) {
  background-color: rgba(255, 255, 255, 0.25) !important;
  transform: translateY(0);
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.2);
}

/* 用户信息容器 - 靠右显示 */
.user-info-container {
  display: flex;
  align-items: center;
  height: 60px;
  padding: 0 20px;
  flex-shrink: 0;
  position: absolute;
  right: 0;
  top: 0;
  z-index: 1000;
  gap: 12px;
}

.theme-toggle {
  display: flex;
  align-items: center;
  padding: 4px 8px;
  border-radius: 999px;
  background-color: rgba(255, 255, 255, 0.18);
  border: 1px solid rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(6px);
}

.theme-toggle :deep(.el-switch__core) {
  width: 52px;
  height: 26px;
  border-color: transparent;
  background-color: rgba(255, 255, 255, 0.2);
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.15);
}

.theme-toggle :deep(.el-switch__label) {
  color: var(--header-text-color);
  font-size: 12px;
  transition: color 0.2s ease;
}

.theme-toggle :deep(.el-switch.is-checked .el-switch__core) {
  background-color: rgba(15, 23, 42, 0.65);
  box-shadow: inset 0 0 0 1px rgba(15, 23, 42, 0.35);
}

.theme-toggle :deep(.el-switch__action) {
  width: 20px;
  height: 20px;
  margin-top: -10px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25);
  background-color: #fff;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--header-text-color);
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.user-icon {
  font-size: 18px;
}

.username {
  font-size: 14px;
  white-space: nowrap;
}

/**
 * ==================== 过渡动画样式 ====================
 */

/* 侧边栏滑入动画 */
.sidebar-slide-enter-from,
.sidebar-slide-leave-to {
  transform: translateX(-220px);
  /* 从左侧滑出 */
  opacity: 0;
  /* 透明度为 0 */
}

.sidebar-slide-enter-active,
.sidebar-slide-leave-active {
  transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s ease, box-shadow 0.4s ease;
  /* 平滑过渡 */
}

.sidebar-slide-enter-to,
.sidebar-slide-leave-from {
  transform: translateX(0);
  /* 回到原位置 */
  opacity: 1;
  /* 完全不透明 */
}

/* 侧边栏阴影效果 */
.sidebar-container {
  box-shadow: 0 0 0 rgba(0, 0, 0, 0);
  /* 初始无阴影 */
}

.sidebar-slide-enter-to .sidebar-container,
.sidebar-slide-leave-from .sidebar-container {
  box-shadow: 6px 0 20px rgba(0, 0, 0, 0.18);
  /* 滑入后显示阴影 */
}

/**
 * ==================== 无障碍支持 ====================
 */

/* 用户偏好：减少动画时禁用复杂动效 */
/* 当用户系统设置偏好减少动画时，禁用所有过渡和动画效果 */
@media (prefers-reduced-motion: reduce) {
  /* 禁用所有过渡动画 */
  .sidebar-slide-enter-active,
  .sidebar-slide-leave-active {
    transition: none !important;
  }

  /* 禁用所有变换和滤镜效果 */
  .sidebar-slide-enter-from,
  .sidebar-slide-leave-to {
    transform: none !important;
    opacity: 1 !important;
  }
}

/**
 * ==================== 侧边栏样式 ====================
 */

/* 侧边栏容器样式 - 防止滚动条 */
.sidebar-container {
  overflow: hidden !important;
  /* 隐藏溢出内容，防止出现滚动条 */
  background-color: var(--sidebar-bg-color);
  transition: background-color 0.3s ease;
}

/* 侧边栏菜单容器 */
:deep(.el-menu-vertical-demo) {
  overflow: hidden !important;
  width: 100%;
  background-color: transparent;
}

/* 侧边栏菜单项基础样式 */
:deep(.el-menu-vertical-demo .el-menu-item) {
  transition: all 0.3s ease;
  /* 过渡动画 */
  border-radius: 4px;
  /* 圆角 */
  position: relative;
  overflow: hidden;
  width: 100%;
  box-sizing: border-box;
}

/* 侧边栏菜单项悬停样式 */
:deep(.el-menu-vertical-demo .el-menu-item:hover) {
  background-color: rgba(255, 208, 75, 0.2) !important;
  /* 金色半透明背景 */
  color: #ffd04b !important;
  /* 金色文字 */
  transform: translateX(4px);
  /* 向右移动 4px */
  padding-left: 24px !important;
  margin-right: -4px;
  /* 补偿移动，防止溢出 */
}

/* 侧边栏菜单项激活（选中）样式 */
:deep(.el-menu-vertical-demo .el-menu-item.is-active) {
  background-color: rgba(255, 208, 75, 0.3) !important;
  /* 更深的金色背景 */
  color: #ffd04b !important;
  /* 金色文字 */
  font-weight: 600;
  /* 加粗 */
  border-left: 3px solid #ffd04b;
  /* 左侧金色边框 */
}

/* 侧边栏菜单项点击效果 */
:deep(.el-menu-vertical-demo .el-menu-item:active) {
  background-color: rgba(255, 208, 75, 0.4) !important;
  /* 最深的金色背景 */
  transform: translateX(2px);
  /* 向右移动 2px */
  box-shadow: inset 2px 0 4px rgba(255, 208, 75, 0.3);
  /* 内阴影 */
}

/* 侧边栏菜单项左侧指示条（伪元素） */
:deep(.el-menu-vertical-demo .el-menu-item::before) {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 0;
  /* 初始宽度为 0 */
  background-color: #ffd04b;
  /* 金色 */
  transition: width 0.3s ease;
  /* 宽度过渡动画 */
}

/* 激活状态的菜单项显示指示条 */
:deep(.el-menu-vertical-demo .el-menu-item.is-active::before) {
  width: 3px;
  /* 激活时宽度为 3px */
}

/* 顶部导航栏所有菜单项的通用样式 */
:deep(.el-menu--horizontal .el-menu-item) {
  transition: all 0.3s ease;
  border-radius: 4px;
  margin: 0 4px;
  position: relative;
}

:deep(.el-menu--horizontal .el-menu-item:hover) {
  background-color: rgba(255, 255, 255, 0.15) !important;
}

:deep(.el-menu--horizontal .el-menu-item.is-active) {
  background-color: rgba(255, 255, 255, 0.2) !important;
  color: #ffd04b !important;
  font-weight: 600;
}

:deep(.el-menu--horizontal .el-menu-item:active) {
  background-color: rgba(255, 255, 255, 0.25) !important;
  transform: scale(0.98);
}

/*
.common-layout {
  max-width: 1897px;
  max-height: 1070px;
} */
</style>
